package com.jia.lidao.others.ui;


import android.app.Activity;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Dimension;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.Projection;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.LatLngBounds;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.jia.lidao.R;
import com.jia.lidao.UserUtils;
import com.jia.lidao.network.http.BusinessManager;
import com.jia.lidao.network.http.MyCallback;
import com.jia.lidao.network.http.request.impl.ModifyLocationRequest;
import com.jia.lidao.others.utils.DisplayUtil;
import com.jia.lidao.ui.BaseActivity;
import com.jia.lidao.utils.LogUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * AMapV1地图中介绍如何显示世界图
 */
public class BasicMapActivity extends BaseActivity implements LocationSource,
        AMapLocationListener {

    @BindView(R.id.ib_back)
    ImageView ibBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_address_detailed)
    TextView tvAddressDetailed;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    private MapView mapView;
    private AMap aMap;
    private int merchant_id;
    private String street;

    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private AMapLocation amapLocation;
    private GeocodeSearch geocoderSearch;
    private Boolean isFirstIn = true;
    double latitude = 0;
    double longitude = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.basicmap_activity);
        ButterKnife.bind(this);
        String param = getIntent().getStringExtra("param");
        try {
            JSONObject jsonObject = new JSONObject(param);
            latitude = jsonObject.getDouble("latitude");
            longitude = jsonObject.getDouble("longitude");
            merchant_id = jsonObject.getInt("merchant_id");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        tvTitle.setText("地址");
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        init();
        LogUtil.printJ("merchant_id="+merchant_id+"agent id="+UserUtils.getInstance().getAgent().merchant_id);
        if(merchant_id!= UserUtils.getInstance().getAgent().merchant_id){
            tvSure.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 初始化AMap对象
     */
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }

        geocoderSearch = new GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
                if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                    if (result != null && result.getRegeocodeAddress() != null
                            && result.getRegeocodeAddress().getFormatAddress() != null) {
                        String addressName = result.getRegeocodeAddress().getFormatAddress()
                                + "附近";
                        tvAddress.setText(result.getRegeocodeAddress().getCity());
                        street = result.getRegeocodeAddress().getFormatAddress();
                        tvAddressDetailed.setText(addressName);
                    }
                }
            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

            }
        });
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        geocoderSearch = null;
    }

/*	public void onClick(View v) {
        switch (v.getId()) {
		case R.id.basicmap:
			aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
			break;
		case R.id.rsmap:
			aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 卫星地图模式
			break;
		}
		
	}*/


    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.map_marker_layout, null);
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromView(view));// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        //myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        //myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        // myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        //myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        // aMap.setMyLocationStyle(myLocationStyle);
        // Marker.setPositionByPixels(int x,int y)
        BitmapDescriptor descriptor = BitmapDescriptorFactory.fromResource(R.mipmap.address_site_up);
        MarkerOptions markerOption = new MarkerOptions().icon(descriptor)
                .draggable(true);


        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // aMap.setMyLocationType()

        Marker marker = aMap.addMarker(markerOption);
        if (latitude != 0) {
            marker.setPositionByPixels(DisplayUtil.getScreenWidth(getApplicationContext()) / 2, DisplayUtil.getScreenHeight(getApplicationContext()) / 2);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(latitude, longitude)));
        } else {
            marker.setPositionByPixels(DisplayUtil.getScreenWidth(getApplicationContext()) / 2, DisplayUtil.getScreenHeight(getApplicationContext()) / 2);
        }

        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));

    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {

        if (mListener != null && amapLocation != null) {

            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                if (isFirstIn) {
                    isFirstIn = false;
                    //  aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude())));
                }
                this.amapLocation = amapLocation;

                toGeoLocation();
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }


    @OnClick({R.id.ib_back, R.id.tv_location})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ib_back:
                finish();
                break;
            case R.id.tv_location:
                if (null != amapLocation) {
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude())));
                }
                break;
        }
    }

    @OnClick(R.id.tv_sure)
    public void onViewClicked() {
        showDialog("");
        BusinessManager.getInstance().changeLocation(new ModifyLocationRequest(merchant_id, street, longitude, latitude), new MyCallback<Void>() {
            @Override
            public void onSuccess(Void result, String message) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showToast("更新店铺地址成功");
                        dismissDialog();
                        setResult(RESULT_OK);
                        finish();
                    }
                },300);

            }

            @Override
            public void onError(String errorCode, String message) {
                showToast("更新店铺地址失败");
                dismissDialog();
            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onRefreshToken() {

            }
        });
    }


    private void toGeoLocation() {
        Point mPoint = new Point(DisplayUtil.getScreenWidth(getApplicationContext()) / 2, DisplayUtil.getScreenHeight(getApplicationContext()) / 2);
        LatLng mLatlng = aMap.getProjection().fromScreenLocation(mPoint);
        LatLonPoint latLonPoint = new LatLonPoint(mLatlng.latitude, mLatlng.longitude);
        latitude = mLatlng.latitude;
        longitude = mLatlng.longitude;
        LogUtil.printJ("latitude=" + latitude + " longitude=" + longitude);
        getAddress(latLonPoint);
    }

    /**
     * 响应逆地理编码
     */
    public void getAddress(LatLonPoint latLonPoint) {
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200,
                GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        geocoderSearch.getFromLocationAsyn(query);// 设置异步逆地理编码请求
    }


}
